package com.shenghui.enterprise.base.service.impl;
import com.alibaba.fastjson.JSONObject;
import com.shenghui.enterprise.base.entity.BaseModule;
import com.shenghui.enterprise.base.entity.EntityCommon;
import com.shenghui.enterprise.utils.GeneralUtil;
import com.shenghui.enterprise.utils.UserUtil;
import com.shenghui.enterprise.vo.Result;
import com.shenghui.enterprise.base.mapper.BaseModuleMapper;
import com.shenghui.enterprise.base.mapper.BaseRoleModuleMapper;
import com.shenghui.enterprise.base.service.IBaseModuleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 模块业务逻辑实现类
 * @Author houjh
 * @Email: happyxiaohou@gmail.com
 * @Date: 2020-05-29
 * @Copyright (c) 2020-2022 云南昇晖科技有限公司
 */
@Service
@Transactional
public class BaseModuleServiceImpl extends ServiceImpl<BaseModuleMapper, BaseModule> implements IBaseModuleService {

    @Autowired
    private BaseModuleMapper baseModuleMapper;
    @Autowired
    private BaseRoleModuleMapper baseRoleModuleMapper;    //模块和角色的关联
    @Autowired
    private EntityCommon entityCommon;

    @Autowired
    private UserUtil userUtil;

    @Override
    public Object getBaseModuleTreeList(Map map) {
        String parentId = null;
        if (GeneralUtil.isNotNull(map.get("id"))) {
            parentId = map.get("id").toString();
        }
        List<Map> list = baseModuleMapper.getBaseModuleTreeList(parentId);
        if (list != null && list.size() > 0) {
            for (Map m : list) {
                //判断是否有子集
                List<Map> result = baseModuleMapper.getBaseModuleTreeList(m.get("moduleId").toString());
                if(result != null && result.size() > 0){
                    m.put("isParent",true);
                } else {
                    m.put("isParent",false);
                }
                m.put("id", m.get("moduleId"));
                m.put("name", m.get("name"));
                m.put("orderValue", m.get("orderValue"));
                m.put("parentId", m.get("parentId"));
            }
            return list;
        }
        return null;
    }

    @Override
    @Transactional
    public Result deleteBaseModule(String id) {
        //删除模块信息
        baseModuleMapper.deleteById(id);
        //删除模块和角色的关联关系表
        Map<String,Object> params = new HashMap<>();
        params.put("module_id",id);
        baseRoleModuleMapper.deleteByMap(params);
        return Result.ok("模块删除成功!");
    }

    @Override
    @Transactional
    public Object updateBaseModuleOrder(String id, Integer orderValue) {
        if(StringUtils.isEmpty(id)){
            return Result.error("必填参数【id】不能为空");
        }
        if(StringUtils.isEmpty(orderValue)){
            return Result.error("必填参数【orderValue】不能为空");
        }
        BaseModule module = new BaseModule();
        module.setModuleId(id);
        module.setOrderValue(orderValue);
        this.updateById(module);
        return Result.ok("模块排序值修改成功");
    }

    @Override
    @Transactional
    public Result addBaseModule(BaseModule module, String id) {
        JSONObject json = new JSONObject();
        String action_msg = "";
        if (GeneralUtil.isNull(module.getParentId())) {
            module.setParentId("0");
        }
        if (GeneralUtil.isNotNull(module.getUrl())) {
            module.setUrl(module.getUrl().replace("!and!", "&"));
        }
        if (GeneralUtil.isNull(id)) {
            entityCommon.createBase(module);
            int i = baseModuleMapper.insert(module);
            if (i > 0) {
                action_msg = "模块添加成功";
            }
        } else {
            module.setModuleId(id);
            int i = baseModuleMapper.updateById(module);
            if (i > 0) {
                action_msg = "模块修改成功";
            }
        }
        return Result.ok( action_msg, module);
    }

    @Override
    public Map<String, Object> getBaseModuleById(String id) {
        return baseModuleMapper.getBaseModuleById(id);
    }

    @Override
    public Object topModule(Map map, HttpServletRequest request, HttpServletResponse response) {
        //设置用户模块和操作权限
        List<Map<String, Object>> userModules = baseModuleMapper.getModuleTreeByUserId(userUtil.getUserId(), "");
        return userModules;
    }

    @Override
    public Object childsModule(String parentId, HttpServletRequest request, HttpServletResponse response) {
        //设置用户模块和操作权限
        List<Map<String, Object>> userModules = baseModuleMapper.getModuleTreeByUserId(userUtil.getUserId(), parentId); // 二级
        userModules = moduleIteration(userUtil.getUserId(), userModules, 0);
        return userModules;
    }

    /**
     * 模块迭代查询
     */
    public List<Map<String, Object>> moduleIteration(String userId, List<Map<String, Object>> modules, Integer iterationNUm){
        iterationNUm ++;
        // 从第二层开始在查询三层
        // 查询五层后 迭代停止
        if (iterationNUm < 4 ) {
            for (int i = 0; i < modules.size(); i++) {
                List<Map<String, Object>> baseModulesChilds = baseModuleMapper.getModuleTreeByUserId(userId, modules.get(i).get("moduleId").toString());
                List<Map<String, Object>> childsModules = moduleIteration(userId, baseModulesChilds, iterationNUm);
                modules.get(i).put("childs", childsModules);
            }
        }
        return modules;
    }
}
